package ch.ethz.fcl.overlays;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

import android.content.Context;
import android.graphics.Canvas;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import ch.ethz.fcl.draw.GeoBounds;
import ch.ethz.fcl.udp.Protocal;
import ch.ethz.fcl.udp.UDPClient;

public class MetroBuzzOverlay extends Overlay {
	private final String TAG = "Metro Buzz Overlay";
	Context mContext = null;
	View main_view = null;
	private UDPClient client;
	private String msg = "MetroBuzz:Control:";
	private String mode = Protocal.FINGERUP;

	public MetroBuzzOverlay(Context context) {
		super();
		mContext = context;
		client = new UDPClient();
	}

	public void draw(Canvas canvas, MapView view, boolean shadow) {
		Log.d(TAG, "Draw");
		view.invalidate();
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event, MapView view) {
		view.invalidate();
		Log.d(TAG, "Key up");
		return true;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event, MapView mapView) {
		msg = "MetroBuzz:Control:";
		if (mapView.getZoomLevel() <= 11) {
			mapView.getController().setZoom(11);
			final int action = event.getAction();
			switch (action & MotionEvent.ACTION_MASK) {
			case MotionEvent.ACTION_DOWN:
				mode = Protocal.DRAG;
				break;
			case MotionEvent.ACTION_UP:
			case MotionEvent.ACTION_POINTER_UP:
				mode = Protocal.FINGERUP;
			case MotionEvent.ACTION_MOVE:
				if (mode == Protocal.DRAG) {
					// return true;
				} else if (mode.equals(Protocal.ZOOM)) {

				}
				break;
			case MotionEvent.ACTION_POINTER_DOWN:
				mode = Protocal.ZOOM;
			}
		} else if (mapView.getZoomLevel() >= 16) {
			mapView.getController().setZoom(16);
		}

		sendMapInfo(mapView);
		return super.onTouchEvent(event, mapView);
	}

	public void sendMapInfo(MapView view) {
		GeoPoint center = (GeoPoint) view.getMapCenter();
		float centerCoorX = GeoBounds.getBoundLon(center.getLongitudeE6());
		float centerCoorY = GeoBounds.getBoundLat(center.getLatitudeE6());

		if (centerCoorX > 1 || centerCoorX < 0)
			centerCoorX = 0.5f;

		if (centerCoorY > 1 || centerCoorY < 0)
			centerCoorY = 0.5f;
		msg += Protocal.MAP + ":" + centerCoorX + ":" + centerCoorY + ":"
				+ view.getZoomLevel();
		client.setMessage(msg);
		client.run();
	}
}
